﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agile.Manager.Util;
using System.Collections.ObjectModel;
using Agile.Manager.Windows.Model;
using Agile.Manager.SQLite;
using System.Windows.Input;
using Agile.Manager.Utilities.UI;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Agile.Manager.Hub;

namespace Agile.Manager.UI.Windows.ViewModel
{
    public class TaskViewModel : ObservableObject
    {
        SQLiteDataManagement sql = new SQLiteDataManagement();

        public TaskViewModel()
        {
         
        }

        public ICommand SelectClientChange
        {
            get
            {
                return new DelegateCommand<EventArgs>((e) =>
                {
                    RoutedPropertyChangedEventArgs<Object> newValue = e as RoutedPropertyChangedEventArgs<Object>;
                    if (newValue != null)
                    {
                        Task mess = newValue.NewValue as Task;
                        if (mess != null)
                        {
                            SelectedTask = mess;
                            SelectedSubTask = null;
                        }
                        else
                        {
                            Task item = newValue.NewValue as Task;
                            if (item != null)
                            {
                                SelectedSubTask = item;
                            }
                        }

                        Error = "";
                    }
                }
                );
            }
        }

        string _forecolor;
        public string MessageForeColor
        {
            get { return _forecolor; }
            private set
            {
                _forecolor = value;
                RaisePropertyChanged("MessageForeColor");
            }
        }

        string _error;
        public string Error
        {
            get
            {
                return _error;
            }
            private set
            {
                _error = value;
                RaisePropertyChanged("Error");
            }
        }

        public Task SelectedTask { get; set; }
        public Task SelectedSubTask { get; set; }

        
        public ICommand TaskNameChanged
        {
            get
            {
                return new DelegateCommand<EventArgs>((e) =>
                {
                    TextBox oa = ((System.Windows.RoutedEventArgs)(e)).OriginalSource as TextBox;
                    _tempTaskName = oa.Text;
                });
            }
        }

        private string _tempTaskName = string.Empty;

        public ICommand SaveTask
        {
            get
            {
                return new DelegateCommand<EventArgs>((e) =>
                {
                    try
                    {
                        Button oa = ((System.Windows.RoutedEventArgs)(e)).OriginalSource as Button;
                        TreeViewItem tvi = FindAncestor<TreeViewItem>((DependencyObject)oa);
                        tvi.IsSelected = true;
                        SelectedTask.Name = _tempTaskName;
                        sql.Save<Task>(SelectedTask);
                        //MessageBox.Show("Task Saved!", "Saved", MessageBoxButton.OK, MessageBoxImage.Information);
                        RaisePropertyChanged("GetParentTasks");
                        MessageForeColor = "Green";
                        Error = "Task Saved!";
                    }
                    catch (Exception)
                    {
                        MessageForeColor = "Red";
                        Error = "Error Saving the Task";
                    }
                });
            }
        }

        public ICommand NewTask
        {
            get
            {
                return new DelegateCommand<EventArgs>((e) =>
                {
                    try
                    {
                        Task newT = new Task();
                        GetParentTasks.Add(newT);
                        sql.Save<Task>(newT);
                        RaisePropertyChanged("GetParentTasks");
                    }
                    catch (Exception)
                    {
                        MessageForeColor = "Red";
                        Error = "Error Adding a new Task";
                    }
                });
            }
        }

        public ICommand NewSubTask
        {
            get
            {
                return new DelegateCommand<EventArgs>((e) =>
                {
                    try
                    {
                        Button oa = ((System.Windows.RoutedEventArgs)(e)).OriginalSource as Button;
                        TreeViewItem tvi = FindAncestor<TreeViewItem>((DependencyObject)oa);
                        tvi.IsSelected = true;
                        Task newT = new Task();
                        newT.TaskID = SelectedTask.ID;
                        SelectedTask.Subtasks.Add(newT);
                        sql.Save<Task>(newT);
                        RaisePropertyChanged("GetParentTasks");
                    }
                    catch (Exception)
                    {
                        MessageForeColor = "Red";
                        Error = "Error Adding a new SubTask";
                    }
                });
            }
        }

        public ICommand DeleteTask
        {
            get
            {
                return new DelegateCommand<EventArgs>((e) =>
                {
                    try
                    {
                        Button oa = ((System.Windows.RoutedEventArgs)(e)).OriginalSource as Button;
                        TreeViewItem tvi = FindAncestor<TreeViewItem>((DependencyObject)oa);
                        tvi.IsSelected = true;
                        MessageBoxResult messResult = MessageBox.Show("Are you sure to delete the Task?", "Are you sure?", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                        if (messResult == MessageBoxResult.Yes)
                        {
                            DeleteTaskInfo(SelectedTask);
                            sql.Delete<Task>(SelectedTask);
                            MessageBox.Show("Task deleted!", "Deleted", MessageBoxButton.OK, MessageBoxImage.Information);
                            RaisePropertyChanged("GetParentTasks");
                        }
                    }
                    catch (Exception)
                    {
                        MessageForeColor = "Red";
                        Error = "Error Deleting the Task";
                    }
                });
            }
        }

        public ICommand TaskEditInfo
        {
            get
            {
                return new DelegateCommand<EventArgs>((e) =>
                {
                    try
                    {
                        Button oa = ((System.Windows.RoutedEventArgs)(e)).OriginalSource as Button;
                        TreeViewItem tvi = FindAncestor<TreeViewItem>((DependencyObject)oa);
                        tvi.IsSelected = true;
                        TaskHub.EditDetailInfo(SelectedTask);
                    }
                    catch (Exception)
                    {
                        MessageForeColor = "Red";
                        Error = "Error Saving the Task";
                    }
                });
            }
        }

        private void DeleteTaskInfo(Task SelectedTask)
        {
            foreach (Task item in SelectedTask.Subtasks)
            {
                sql.Delete<Task>(item);
            }
        }

        private static T FindAncestor<T>(DependencyObject current)
            where T : DependencyObject
        {
            do
            {
                if (current is T)
                {
                    return (T)current;
                }
                current = VisualTreeHelper.GetParent(current);
            }
            while (current != null);
            return null;
        }
        
        public ObservableCollection<Task> GetParentTasks
        {
            get
            {
                List<Task> _list = new List<Task>();
                foreach (var item in sql.GetData<Task>())
                {
                    if (string.IsNullOrEmpty(item.TaskID))
                    {
                        item.Subtasks = GetChildren(item);
                        _list.Add(item); 
                    }
                }

                if (_list.Count == 0) _list.Add(new Task());

                return new ObservableCollection<Task>(_list);
            }
        }

        private List<Task> GetChildren(Task _task)
        {
            List<Task> _list = new List<Task>();
                foreach (var item in sql.GetData<Task>())
                {
                    if (!string.IsNullOrEmpty(item.TaskID))
                        if (item.TaskID == _task.ID)
                            _list.Add(item);
                }

                return _list;
        }

    }
}
